/**
 * Copyright (c) 2015-2017, Javen Zhou  (javen205@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

package com.javen.weixin.controller;

import com.javen.weixin.Interceptor.ConfigInterceptor;
import com.javen.weixin.common.model.Qrcode;
import com.javen.weixin.service.QrcodeService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.QrcodeApi;

/**
 * @author Javen 2017年7月14日
 *expire_seconds=0 为永久有效
 */
@Before(ConfigInterceptor.class)
public class QrcodeController extends Controller {
	static Log log = Log.getLog(QrcodeController.class);
	static QrcodeService qs = QrcodeService.me;

	@Clear
	public void index() {
		renderText("感谢您使用weixin_pro之微信推广支付 -By Javen205");
	}

	/**
	 * 临时二维码
	 */
	public void createTemporary() {
		// 场景值ID，临时二维码时为32位非0整型
		int sceneId = getParaToInt("sceneId", 1);
		// 最大不超过604800（即7天）
		int expireSeconds = getParaToInt("expireSeconds", 604800);
		Qrcode qrcode = null;
		String appId = ApiConfigKit.getAppId();
		qrcode = qs.getQrcodeBySceneId(sceneId, appId);
		String url = showQrCode(qrcode);
		if (StrKit.notBlank(url)) {
			redirect(url);
			return;
		}
		
		ApiResult apiResult = QrcodeApi.createTemporary(expireSeconds, sceneId);
log.info(apiResult.getJson());
		if (apiResult.isSucceed()) {
			url = apiResult.getStr("url");
			String ticket = apiResult.getStr("ticket");
			int expire_seconds = apiResult.getInt("expire_seconds");
			// 保存记录
			qs.save(qrcode,appId, expire_seconds, ticket, sceneId, "", url);
			renderQrCode(url, 300, 300);
		} else {
			renderJson(apiResult);
		}
	}

	/**
	 * 永久二维码
	 */
	public void createPermanent() {
		// 场景值ID，字符串类型，长度限制为1到64
		String sceneStr = getPara("sceneStr");
		// 最大值为100000（目前参数只支持1--100000）
		int sceneId = getParaToInt("sceneId", 1);
		Qrcode qrcode = null;
		String appId = ApiConfigKit.getAppId();
		
		ApiResult apiResult = null;
		if (StrKit.isBlank(sceneStr)) {
			//根据sceneId以及appId 查询
			qrcode = qs.getQrcodeBySceneId(sceneId, appId);
			String url = showQrCode(qrcode);
			if (StrKit.notBlank(url)) {
				redirect(url);
				return;
			}
			apiResult = QrcodeApi.createPermanent(sceneId);
		} else {
			//根据sceneStr以及appId 查询
			qrcode = qs.getQrcodeBySceneStr(sceneStr, appId);
			String url = showQrCode(qrcode);
			if (StrKit.notBlank(url)) {
				renderQrCode(url, 300, 300);
				return;
			}
			apiResult = QrcodeApi.createPermanent(sceneStr);
		}
log.info(apiResult.getJson());
		if (apiResult.isSucceed()) {
			String url = apiResult.getStr("url");
			String ticket = apiResult.getStr("ticket");
			// 保存记录
			qs.save(qrcode,appId, 0, ticket, sceneId, sceneStr, url);
			renderQrCode(url, 300, 300);
		} else {
			renderJson(apiResult);
		}
	}
	/**
	 * 根据ticket查询二维码
	 */
	@Clear
	public void getQrCode() {
		int id = getParaToInt("id");
		String ticket = getPara("ticket");
		if (StrKit.isBlank(ticket)) {
			Qrcode qrcode = qs.getQrcodeById(id);
			if (null == qrcode) {
				renderText("未查到对应的二维码");
				return;
			}
			ticket = qrcode.getTicket();
		}
		String url = QrcodeApi.getShowQrcodeUrl(ticket);
		renderQrCode(url, 300, 300);
	}
	
	/**
	 * 根据ticket 显示二维码
	 */
	public void showQrCode() {
		String ticket = getPara("ticket");
		if (StrKit.isBlank(ticket)) {
			renderText("ticket is null");
			return;
		}
		
		Qrcode qrcode = qs.getQrcodeByTicket(ticket, ApiConfigKit.getAppId());
		if (null == qrcode) {
			renderText("未查到对应的二维码");
			return;
		}
		
		String url = QrcodeApi.getShowQrcodeUrl(qrcode.getTicket());
		renderQrCode(url, 300, 300);
	}
	
	
	/**
	 * 通过qrcode判断ticket是否过期，若没有过期就通过ticket获取二维码
	 * @param qrcode
	 */
	public String showQrCode(Qrcode qrcode) {
		if (null != qrcode ) {
			Integer expireSeconds = qrcode.getExpireSeconds();
			long updateTime = qrcode.getUpdateTime().getTime();
			long currentTime = System.currentTimeMillis()/1000;//转化为秒
			//判断ticket是否过期
			if (currentTime - updateTime < expireSeconds) {
				String url = QrcodeApi.getShowQrcodeUrl(qrcode.getTicket());
log.info("二维码url>"+url);				
				return url;
			}else {
log.info("二维码ticket过期了...");				
			}
		}
		return null;
	}
}
